<template>
  <div class="in-out-record">
    <!-- 搜索区域 -->
    <el-card class="search-card" :class="{ 'search-active': isSearchActive }">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入商品名称" 
            clearable
            @focus="handleSearchFocus"
            @blur="handleSearchBlur"
          />
        </el-form-item>
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="item in operationTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <div class="option-item">
                <el-icon>
                  <component :is="item.icon" />
                </el-icon>
                <span>{{ item.label }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span class="title">出入库记录</span>
          <div class="header-right">
            <el-button type="success" @click="exportRecords" :loading="exporting">
              <el-icon><Download /></el-icon>导出记录
            </el-button>
            <el-radio-group v-model="viewType" size="small">
              <el-radio-button :value="'table'">表格视图</el-radio-button>
              <el-radio-button :value="'timeline'">时间线视图</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <!-- 表格视图 -->
      <template v-if="viewType === 'table'">
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="createTime" label="操作时间" width="180" />
          <el-table-column prop="type" label="操作类型" width="120">
            <template #default="{ row }">
              <el-tag
                :type="getOperationTypeTag(row.type)"
                effect="dark"
                class="type-tag"
              >
                <el-icon class="type-icon">
                  <component :is="getOperationTypeIcon(row.type)" />
                </el-icon>
                {{ getOperationTypeText(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="quantity" label="数量" width="120" align="center">
            <template #default="{ row }">
              <span :class="['quantity', row.type === 'out' ? 'decrease' : 'increase']">
                {{ row.type === 'out' ? '-' : '+' }}{{ row.quantity }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="操作人" width="120" />
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </template>

      <!-- 时间线视图 -->
      <template v-else>
        <div class="timeline-container">
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in tableData"
              :key="index"
              :type="getOperationTypeTag(record.type)"
              :timestamp="record.createTime"
              :hollow="index !== 0"
              size="large"
            >
              <div class="timeline-content" :class="{ 'fade-in': true, 'slide-right': index % 2 === 0, 'slide-left': index % 2 !== 0 }">
                <h4 class="timeline-title">
                  <el-icon class="type-icon">
                    <component :is="getOperationTypeIcon(record.type)" />
                  </el-icon>
                  {{ getOperationTypeText(record.type) }}
                </h4>
                <div class="timeline-info">
                  <p class="product-name">商品：{{ record.productName }}</p>
                  <p class="quantity" :class="record.type === 'out' ? 'decrease' : 'increase'">
                    数量：{{ record.type === 'out' ? '-' : '+' }}{{ record.quantity }}
                  </p>
                  <p class="operator">操作人：{{ record.operator }}</p>
                  <p class="remark">备注：{{ record.remark }}</p>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </template>
    </el-card>

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="记录详情"
      size="40%"
      destroy-on-close
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="操作时间">{{ currentRecord.createTime }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getOperationTypeTag(currentRecord.type)">
            {{ getOperationTypeText(currentRecord.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ currentRecord.productName }}</el-descriptions-item>
        <el-descriptions-item label="数量">
          <span :class="['quantity', currentRecord.type === 'out' ? 'decrease' : 'increase']">
            {{ currentRecord.type === 'out' ? '-' : '+' }}{{ currentRecord.quantity }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="操作人">{{ currentRecord.operator }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ currentRecord.remark }}</el-descriptions-item>
      </el-descriptions>

      <template v-if="currentRecord.snapshots">
        <el-divider>操作前后库存快照</el-divider>
        <div class="snapshot-comparison">
          <div class="snapshot before">
            <h4>操作前</h4>
            <p>库存数量：{{ currentRecord.snapshots.before }}</p>
          </div>
          <el-icon class="arrow"><ArrowRight /></el-icon>
          <div class="snapshot after">
            <h4>操作后</h4>
            <p>库存数量：{{ currentRecord.snapshots.after }}</p>
          </div>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search, Refresh, Download, ArrowRight,
  Plus, Minus, Edit, Box
} from '@element-plus/icons-vue'

// 搜索相关
const isSearchActive = ref(false)
const searchForm = ref({
  name: '',
  type: '',
  dateRange: []
})

// 表格相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const viewType = ref<'table' | 'timeline'>('table')
const exporting = ref(false)

// 抽屉相关
const drawerVisible = ref(false)
const currentRecord = ref<any>({})

// 操作类型选项
const operationTypes = [
  { value: 'in', label: '入库', icon: Plus },
  { value: 'out', label: '出库', icon: Minus },
  { value: 'adjust', label: '调整', icon: Edit }
]

// 期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 模拟数据
const tableData = ref([
  {
    id: '1',
    createTime: '2023-11-28 10:00:00',
    type: 'in',
    productName: '现代简约沙发',
    quantity: 100,
    operator: '张三',
    remark: '首次入库',
    snapshots: {
      before: 0,
      after: 100
    }
  },
  {
    id: '2',
    createTime: '2023-11-28 11:00:00',
    type: 'out',
    productName: '现代简约沙发',
    quantity: 20,
    operator: '李四',
    remark: '订单出库',
    snapshots: {
      before: 100,
      after: 80
    }
  },
  {
    id: '3',
    createTime: '2023-11-28 12:00:00',
    type: 'adjust',
    productName: '现代简约沙发',
    quantity: 5,
    operator: '王五',
    remark: '库存盘点调整',
    snapshots: {
      before: 80,
      after: 85
    }
  }
])

// 方法
const handleSearchFocus = () => {
  isSearchActive.value = true
}

const handleSearchBlur = () => {
  isSearchActive.value = false
}

const getOperationTypeTag = (type: string) => {
  const map: Record<string, string> = {
    in: 'success',
    out: 'danger',
    adjust: 'warning'
  }
  return map[type] || 'info'
}

const getOperationTypeText = (type: string) => {
  const map: Record<string, string> = {
    in: '入库',
    out: '出库',
    adjust: '调整'
  }
  return map[type] || '未知操作'
}

const getOperationTypeIcon = (type: string) => {
  const map: Record<string, any> = {
    in: Plus,
    out: Minus,
    adjust: Edit
  }
  return map[type] || Box
}

const tableRowClassName = ({ row }: { row: any }) => {
  return `record-${row.type}`
}

const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    name: '',
    type: '',
    dateRange: []
  }
  handleSearch()
}

const loadData = async () => {
  loading.value = true
  try {
    // 这里调用接口获取数据
    total.value = tableData.value.length
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
}

const handleDetail = (row: any) => {
  currentRecord.value = row
  drawerVisible.value = true
}

const exportRecords = async () => {
  exporting.value = true
  try {
    // 这里实现导出逻辑
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败：', error)
  } finally {
    exporting.value = false
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadData()
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.in-out-record {
  .search-card {
    margin-bottom: 20px;
    transition: all 0.3s;
    
    &.search-active {
      transform: translateY(-5px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      
      .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
      }
    }
  }
  
  .list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 16px;
        font-weight: bold;
      }
      
      .header-right {
        display: flex;
        gap: 16px;
        align-items: center;
      }
    }
    
    .type-tag {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      
      .type-icon {
        font-size: 14px;
      }
    }
    
    .quantity {
      font-weight: bold;
      
      &.increase {
        color: #67c23a;
      }
      
      &.decrease {
        color: #f56c6c;
      }
    }
  }
  
  .timeline-container {
    padding: 20px;
    
    .timeline-content {
      padding: 16px;
      border-radius: 4px;
      background-color: #fff;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      
      &.fade-in {
        animation: fadeIn 0.5s ease-in-out;
      }
      
      &.slide-right {
        animation: slideRight 0.5s ease-in-out;
      }
      
      &.slide-left {
        animation: slideLeft 0.5s ease-in-out;
      }
      
      .timeline-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin: 0 0 12px;
        color: #303133;
        
        .type-icon {
          font-size: 18px;
        }
      }
      
      .timeline-info {
        p {
          margin: 8px 0;
          color: #606266;
          
          &.quantity {
            font-weight: bold;
            
            &.increase {
              color: #67c23a;
            }
            
            &.decrease {
              color: #f56c6c;
            }
          }
        }
      }
    }
  }
  
  .snapshot-comparison {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 20px;
    
    .snapshot {
      text-align: center;
      padding: 16px;
      border-radius: 4px;
      background-color: #f5f7fa;
      flex: 1;
      
      h4 {
        margin: 0 0 8px;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #606266;
      }
    }
    
    .arrow {
      font-size: 24px;
      color: #909399;
      margin: 0 20px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

// 表格行样式
:deep(.record-in) {
  background-color: #f0f9eb;
}

:deep(.record-out) {
  background-color: #fef0f0;
}

:deep(.record-adjust) {
  background-color: #fdf6ec;
}

// 动画
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideRight {
  from {
    transform: translateX(-20px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes slideLeft {
  from {
    transform: translateX(20px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

// 响应式处理
@media screen and (max-width: 768px) {
  .in-out-record {
    .search-form {
      .el-form-item {
        width: 100%;
      }
    }
    
    .snapshot-comparison {
      flex-direction: column;
      
      .arrow {
        transform: rotate(90deg);
        margin: 20px 0;
      }
    }
  }
}

// 添加图标样式
.type-icon {
  margin-right: 8px;
  vertical-align: middle;
  
  &.in {
    color: #67c23a;
  }
  
  &.out {
    color: #f56c6c;
  }
  
  &.adjust {
    color: #e6a23c;
  }
}

.option-item {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .el-icon {
    font-size: 16px;
    color: inherit;
  }
}
</style> 